package com.softstao.guoyu.ui.activity.me;

import android.Manifest;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.igexin.sdk.PushManager;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.softstao.guoyu.R;
import com.softstao.guoyu.base.BaseActivity;
import com.softstao.guoyu.global.SharePreferenceManager;
import com.softstao.guoyu.global.UserManager;
import com.softstao.guoyu.model.me.PersonalInfo;
import com.softstao.guoyu.model.me.User;
import com.softstao.guoyu.model.me.UserCondition;
import com.softstao.guoyu.mvp.interactor.UploadInteractor;
import com.softstao.guoyu.mvp.interactor.me.UserInfoInteractor;
import com.softstao.guoyu.mvp.presenter.UploadPresenter;
import com.softstao.guoyu.mvp.presenter.me.UserInfoPresenter;
import com.softstao.guoyu.mvp.viewer.UploadTargetViewer;
import com.softstao.guoyu.mvp.viewer.me.UpdateInfoViewer;
import com.softstao.guoyu.ui.activity.LoginActivity;
import com.softstao.softstaolibrary.library.utils.LZUtils;
import com.softstao.softstaolibrary.library.widget.CircleImageView;
import com.softstao.softstaolibrary.library.widget.LZToast;
import com.softstao.softstaolibrary.library.widget.progressBar.RoundProgressBarWidthNumber;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.wangjie.androidinject.annotation.annotations.mvp.AIPresenter;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by vaikus on 2017/6/7.
 */

public class UserInfoActivity extends BaseActivity implements UploadTargetViewer, UpdateInfoViewer {

    @AIPresenter(presenter = UploadPresenter.class, interactor = UploadInteractor.class)
    UploadPresenter uploadPresenter;
    @AIPresenter(presenter = UserInfoPresenter.class, interactor = UserInfoInteractor.class)
    UserInfoPresenter presenter;

    @BindView(R.id.avatar)
    CircleImageView avatar;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.referee)
    TextView referee;
    @BindView(R.id.auditDate)
    TextView auditDate;
    @BindView(R.id.level)
    TextView level;
    @BindView(R.id.levelDate)
    TextView levelDate;
    @BindView(R.id.idCardNo)
    TextView idCardNo;
    @BindView(R.id.sex)
    TextView sex;
    @BindView(R.id.mobile)
    TextView mobile;
    @BindView(R.id.wechat)
    TextView wechat;
    @BindView(R.id.qq)
    TextView qq;
    @BindView(R.id.payee)
    TextView payee;
    @BindView(R.id.accountPayee)
    TextView accountPayee;
    @BindView(R.id.openingBank)
    TextView openingBank;
    @BindView(R.id.bond)
    TextView bond;
    @BindView(R.id.progress_layout)
    RelativeLayout progressLayout;
    @BindView(R.id.progress)
    RoundProgressBarWidthNumber progress;
    @BindView(R.id.user_id)
    TextView userId;
    private User user;
    private String level_name, audit_date, level_date;
    private UserCondition condition = new UserCondition();
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm");
    public final static int IMAGE = 100;

    @Override
    public int _ContentView() {
        return R.layout.activity_user_info;
    }

    @Override
    public void initView() {
        initTitle("个人资料");
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {
        user = UserManager.getInstance().getUser();
        if (TextUtils.isEmpty(user.getAvatar())==false) {
            Glide.with(context).load(user.getAvatar()).apply(new RequestOptions().centerCrop()).into(avatar);
        } else {
            avatar.setImageResource(R.mipmap.default_avatar);
        }
        name.setText(user.getName());
        userId.setText("用户ID：" + SharePreferenceManager.getInstance().getAgentId());
        referee.setText(user.getReferee());
        audit_date = user.getAuditDate() == 0 ? "——" : format.format(new Date(user.getAuditDate()));
        auditDate.setText(audit_date);
        switch (User.Type.fromInteger(user.getLevel())) {
            case ANGEL:
                level_name = "天使";
                break;
            case CROWN:
                level_name = "皇冠";
                break;
            case ONE_LEVEL:
                level_name = "一级";
                break;
            case CITY_LEVEL:
                level_name = "市级";
                break;
            case PROVINCE:
                level_name = "省代";
                break;
            case HEADQUARTER:
                level_name = "总部";
                break;
            case UNAGENT:
                level_name = "未授权";
                break;
        }
        level.setText("升级为" + level_name + "时间");
        level_date = user.getLevelDate() == 0 ? "——" : format.format(new Date(user.getLevelDate()));
        levelDate.setText(level_date);
        idCardNo.setText(user.getIdCardNo());
        switch (user.getSex()) {
            case 1:
                sex.setText("男");
                break;
            case 2:
                sex.setText("女");
                break;
        }
        mobile.setText(user.getMobile());
        wechat.setText(user.getWechat());
        qq.setText(user.getQq());
        payee.setText(user.getPayee());
        accountPayee.setText(user.getAccountPayee());
        openingBank.setText(user.getOpeningBank());
        bond.setText(LZUtils.priceFormat(user.getBond()) + "元");
    }

    @OnClick({R.id.avatar, R.id.idCardNo_view, R.id.sex_view, R.id.wechat_view, R.id.qq_view,
            R.id.payee_view, R.id.accountPayee_view, R.id.openingBank_view, R.id.address, R.id.log_out})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.avatar:
                new RxPermissions(this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA)
                        .subscribe(result-> {
                            if (result){
                                PictureSelector.create(UserInfoActivity.this)
                                        .openGallery(PictureMimeType.ofImage())
                                        .selectionMode(PictureConfig.SINGLE)
                                        .previewImage(true)
                                        .isCamera(true)
                                        .enableCrop(true)
                                        .freeStyleCropEnabled(true)
                                        .forResult(IMAGE);
                            }
                        });
                break;
            case R.id.idCardNo_view:
            case R.id.sex_view:
            case R.id.wechat_view:
            case R.id.qq_view:
            case R.id.payee_view:
            case R.id.accountPayee_view:
            case R.id.openingBank_view:
                startActivity(new Intent(context, UserInfoEditActivity.class));
                break;
            case R.id.address:
                startActivity(new Intent(context, AddressListActivity.class));
                break;
            case R.id.log_out:
                CookieSyncManager.createInstance(getApplicationContext());
                CookieManager.getInstance().removeAllCookie();
                SharePreferenceManager.getInstance().setCookie("");
                UserManager.getInstance().setUser(null);
                PushManager.getInstance().unBindAlias(context,String.valueOf(SharePreferenceManager.getInstance().getAgentId()),true);
                SharePreferenceManager.getInstance().setAgentId(0);
                SharePreferenceManager.getInstance().setLoginInfo(null);
                startActivity(new Intent(context, LoginActivity.class));
                finish();
                break;
        }
    }

    @Override
    public void uploadForTarget(String tag, File file) {
        uploadPresenter.uploadForTarget(tag, file, progress);
        progress.setVisibility(View.VISIBLE);
        progressLayout.setVisibility(View.VISIBLE);
    }

    @Override
    public void uploadResult(String tag, String url) {
        switch (tag) {
            case "avatar":
                Glide.with(context).load(url).into(avatar);
                condition.setAvatar(url);
                updateInfo();
                break;
        }
        progress.setVisibility(View.GONE);
        progressLayout.setVisibility(View.GONE);
    }

    @Override
    protected void error(String msg) {
        super.error(msg);
        if (user.getAvatar() != null && !user.getAvatar().equals("")) {
            Glide.with(context).load(user.getAvatar()).into(avatar);
        } else {
            avatar.setImageResource(R.mipmap.default_avatar);
        }
        progress.setVisibility(View.GONE);
        progressLayout.setVisibility(View.GONE);
    }

    @Override
    public void updateInfo() {
        condition.setAgentId(SharePreferenceManager.getInstance().getAgentId());
        presenter.updateInfo(condition);
    }

    @Override
    public void updateResult(PersonalInfo personalInfo) {
        UserManager.getInstance().setUser(personalInfo.getPersonalInfo());
        Glide.with(context).load(UserManager.getInstance().getUser().getAvatar()).apply(new RequestOptions().centerCrop()).into(avatar);
        LZToast.getInstance(context).showToast("修改头像成功");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case IMAGE:
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    uploadForTarget("avatar", new File(selectList.get(0).getCutPath()));
                    break;
            }
        }
    }
}
